package com.eltonkent.dashboard.service.requesthandler;

import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import com.eltonkent.dashboard.constants.ApplicationConstants;
import com.eltonkent.dashboard.data.container.Container;
import com.eltonkent.dashboard.data.container.WeatherContainer;
import com.eltonkent.dashboard.service.helper.HttpServiceHelper;
import com.eltonkent.dashboard.service.responsehandler.YahooWeatherHandler;
import com.eltonkent.dashboard.util.gps.WebResponseNotificationListener;
import com.eltonkent.dashboard.util.logger.Logger;

public class YahooWeatherRequest extends HttpRequest {

	private final String woeid;

	public YahooWeatherRequest(WebResponseNotificationListener listener,
			String woeid) {
		super(listener);
		this.woeid = woeid;
	}

	@Override
	public Container call() throws Exception {
		HttpEntity httpEntity = httpServiceHelper.execute();
		InputStream is = httpEntity.getContent();
		YahooWeatherHandler xmlHandler = new YahooWeatherHandler();
		WeatherContainer container = xmlHandler.deserialize(is);
		Logger.d("TAG", container.toString());
		return container;
	}

	@Override
	public void postExecute(Container t, Throwable throwable) {
		if (t != null) {
			WeatherContainer container = (WeatherContainer) t;
			listener.notifyWeather(container);
		}
	}

	@Override
	public void preExecute() throws Exception {
		Log.i("DBA", "preExecute");
		httpServiceHelper = new HttpServiceHelper(new URI(
				ApplicationConstants.URL_YAHOO_WEATHER));
		List<NameValuePair> requestParameter = new ArrayList<NameValuePair>();
		NameValuePair param = new BasicNameValuePair("w", woeid);
		requestParameter.add(param);
		param = new BasicNameValuePair("u", "c");
		requestParameter.add(param);
		param = new BasicNameValuePair("key",
				ApplicationConstants.API_KEY_YAHOO);
		requestParameter.add(param);
		httpServiceHelper.setRequestParameter(requestParameter);
	}

}
